<template>
  <a-modal v-model:open="open" :title="modelTitle" width="416px" centered :after-close="reset" :body-style="{ padding: '' }" @ok="onOk">
    <a-form ref="formRef" :model="formState" :rules="rules" layout="vertical">
      <a-form-item name="name" label="标签组名称">
        <a-input v-model:value="formState.name" v-trim :maxlength="200" placeholder="请输入标签组名称" />
      </a-form-item>
      <a-form-item name="description" label="标签组描述" class="mb-0">
        <a-textarea v-model:value="formState.description" v-trim :maxlength="200" :rows="3" placeholder="请输入标签组描述" show-count />
      </a-form-item>
    </a-form>
  </a-modal>
</template>

<script lang="ts" setup>
  import type { FormInstance } from 'ant-design-vue'
  import type { Rule } from 'ant-design-vue/es/form'
  import { computed, ref } from 'vue'

  import { dmpTaskApi } from '@/services/api'
  import { validateBitLen, validateDirName } from '@/utils'

  export interface Props {
    afterCloseFn?: () => void
  }

  const props = withDefaults(defineProps<Props>(), {
    afterCloseFn: () => {}
  })

  interface FormState {
    id: string
    name: string
    description: string
  }

  const open = ref(false)
  const modelTitle = computed(() => `${formState.value.id ? '编辑' : '创建'}标签组`)
  const formRef = ref<FormInstance>()
  const formState = ref<FormState>({
    id: '',
    name: '',
    description: ''
  })

  const rules: Record<string, Rule[]> = {
    name: [
      { required: true, trigger: 'change', message: '请输入标签组名称' },
      { validator: validateDirName() },
      { validator: validateBitLen(200), trigger: 'change' }
    ]
  }

  const onOk = async () => {
    await formRef.value?.validateFields()
    const params = {
      id: formState.value.id,
      name: formState.value.name,
      description: formState.value.description
    }
    const handleApi = formState.value.id ? dmpTaskApi.tagGroupEdit : dmpTaskApi.tagGroupAdd
    await handleApi(params, { isAddUid: true })
    open.value = false
    props.afterCloseFn()
  }

  const reset = () => {
    formRef.value?.resetFields()
    formState.value = {
      id: '',
      name: '',
      description: ''
    }
  }

  defineExpose({
    open: (form?: FormState) => {
      if (form) {
        Object.assign(formState.value, form)
      }
      open.value = true
    }
  })
</script>

<style lang="less" scoped></style>
